package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.demo.mapper.MarketUserMapper;
import com.cskaoyan.utils.JacksonUtil;
import com.cskaoyan.utils.MyBatisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user/list")
public class testServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        // 请求方法
        String method = request.getMethod();
        // 请求URL和URI
        String url = request.getRequestURL().toString();
        String uri = request.getRequestURI();

        // 服务器本地的IP和端口号
        String localAddr = request.getLocalAddr();
        int localPort = request.getLocalPort();

        // 应用的上下文路径
        String contextPath = request.getContextPath();
        String queryString = request.getQueryString();//username=zhangsan
        // 请求协议
        String protocol = request.getProtocol();

        String[] queryStrArr = queryString.split("&");
        Map<String,String> infoMap = new HashMap<>();
        for (String temp : queryStrArr) {
            String[] str = temp.split("=");
            infoMap.put(str[0],str[1]);
        }

        int page = Integer.parseInt(infoMap.get("page"));
        int limit = Integer.parseInt(infoMap.get("limit"));
        String username = infoMap.get("username");
        String sort = infoMap.get("sort");
        String order = infoMap.get("order");

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketUserMapper marketUserMapper = sqlSession.getMapper(MarketUserMapper.class);
        String usernameCond = "%" + username + "%";
        List<MarketUser> marketUserListByConditions = marketUserMapper.getMarketUserListByConditions(usernameCond, sort,order,(page-1)*limit, limit);
//        ObjectMapper objectMapper = new ObjectMapper();
//        for (MarketUser marketUserListByCondition : marketUserListByConditions) {
//            String jsonStr = objectMapper.writeValueAsString(marketUserListByCondition);
//            resp.getWriter().write(jsonStr);
//        }
        long total = marketUserListByConditions.size();

        BaseRespVo baseRespVo = BaseRespVo.okList(marketUserListByConditions, total, page, limit);
        // 使用jackson将BaseRespVo对象转换为JSON字符串
        String jsonStr = JacksonUtil.write(baseRespVo);
        // 下一行代码解决响应中文乱码问题：明天会讲
        resp.setContentType("application/json;charset=utf-8");
        // 通过字符输出流写出
        resp.getWriter().println(jsonStr);



    }
}
